package com.kingdee.eas.hr.quali.handler;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.ui.ModelMap;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.data.SortType;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.HistoryConstant;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.bos.metadata.entity.SelectorItemInfo;
import com.kingdee.bos.metadata.entity.SorterItemCollection;
import com.kingdee.bos.metadata.entity.SorterItemInfo;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.base.permission.UserFactory;
import com.kingdee.eas.base.permission.UserInfo;
import com.kingdee.eas.basedata.person.PersonCollection;
import com.kingdee.eas.basedata.person.PersonFactory;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.base.EmpPosOrgRelationCollection;
import com.kingdee.eas.hr.base.EmpPosOrgRelationFactory;
import com.kingdee.eas.hr.base.EmpPosOrgRelationInfo;
import com.kingdee.eas.hr.emp.PersonPositionCollection;
import com.kingdee.eas.hr.emp.PersonPositionFactory;
import com.kingdee.eas.hr.perf.PublicityStatusEnum;
import com.kingdee.eas.hr.quali.QuaApplyPresentLinkEnum;
import com.kingdee.eas.hr.quali.QualiPublicityRelationCollection;
import com.kingdee.eas.hr.quali.QualiPublicityRelationEntryCollection;
import com.kingdee.eas.hr.quali.QualiPublicityRelationEntryInfo;
import com.kingdee.eas.hr.quali.QualiPublicityRelationFactory;
import com.kingdee.eas.hr.quali.QualiPublicityRelationInfo;
import com.kingdee.eas.hr.quali.QualificationApplyBillCollection;
import com.kingdee.eas.hr.quali.QualificationApplyBillFactory;
import com.kingdee.eas.hr.quali.QualificationApplyBillInfo;
import com.kingdee.eas.hr.quali.QualificationManagerCollection;
import com.kingdee.eas.hr.quali.QualificationManagerFactory;
import com.kingdee.eas.hr.quali.SummaryApprovalBillCollection;
import com.kingdee.eas.hr.quali.SummaryApprovalBillFactory;
import com.kingdee.eas.hr.quali.SummaryApprovalBillInfo;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.web.handler.ListHandler;
import com.kingdee.shr.base.syssetting.web.json.JSONUtils;

public class QualiPublicityRelationListHandler extends ListHandler {

    @Override
    protected FilterInfo getDefaultFilter(HttpServletRequest request, HttpServletResponse response)
            throws SHRWebException {
        FilterInfo filerInfo = new FilterInfo();
        Context ctx = SHRContext.getInstance().getContext();
        String userId = ContextUtil.getCurrentUserInfo(ctx).getId().toString();
        String personId = "";
        String uipk = request.getParameter("uipk");
        try {
            UserInfo userInfo = UserFactory.getRemoteInstance().getUserInfo(" where id='" + userId + "' ");
            personId = userInfo.getPerson().getId().toString();
            // PersonPositionCollection pps =
            // PersonPositionFactory.getLocalInstance(ctx)
            // .getPersonPositionCollection(
            // "select personDep.levelTwoGroup.id,company.id where person.id = '"
            // +personId+"'");
            //			
            Date date = new Date();
            EntityViewInfo view = new EntityViewInfo();
            FilterInfo filter = new FilterInfo();
            filter.getFilterItems().add(new FilterItemInfo("assignType", "3", CompareType.NOTEQUALS));
            filter.getFilterItems().add(new FilterItemInfo("person.id", personId));
            filter.getFilterItems().add(new FilterItemInfo("person.employeeType.isInCount", 1));
            filter.getFilterItems().add(
                    new FilterItemInfo(HistoryConstant.EFFDT, date, CompareType.LESS_EQUALS));
            filter.getFilterItems().add(
                    new FilterItemInfo(HistoryConstant.LEFFDT, date, CompareType.GREATER_EQUALS));
            view.setFilter(filter);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add(new SelectorItemInfo("adminOrg.levelTwoGroup.id"));
            sic.add(new SelectorItemInfo("adminOrg.company.id"));
            view.setSelector(sic);
            SorterItemCollection soc = new SorterItemCollection();
            SorterItemInfo info = new SorterItemInfo("assignType");
            info.setSortType(SortType.DESCEND);
            soc.add(info);
            view.setSorter(soc);
            EmpPosOrgRelationCollection epors = EmpPosOrgRelationFactory.getRemoteInstance()
                    .getEmpPosOrgRelationCollection(view);

            QualificationManagerCollection colls = QualificationManagerFactory.getLocalInstance(ctx)
                    .getQualificationManagerCollection("where person.id = '" + personId + "'");
            if ("qualiPublicity".equals(uipk)) {
                if (colls.size() < 1) {
                    filerInfo.getFilterItems().add(
                            new FilterItemInfo("pbulicityStatus", "1", CompareType.EQUALS));
                    String msk = "(";
                    int count = 1;
                    for (int i = 0, size = epors.size(); i < size; i++) {
                        EmpPosOrgRelationInfo eporInfo = epors.get(i);
                        String firstDepId = eporInfo.getAdminOrg().getLevelTwoGroup().getId().toString();
                        String companyId = eporInfo.getAdminOrg().getCompany().getId().toString();
                        filerInfo.getFilterItems().add(
                                new FilterItemInfo("publicOrgIds", "%" + firstDepId + "%", CompareType.LIKE));
                        filerInfo.getFilterItems().add(
                                new FilterItemInfo("publicOrgIds", "%" + companyId + "%", CompareType.LIKE));
                        msk += "#" + count + " or #" + (count + 1) + " OR ";
                        count += 2;
                    }
                    msk = msk.substring(0, msk.length() - 3) + ")";
                    filerInfo.setMaskString("#0 and " + msk);
                } else {
                    filerInfo.getFilterItems().add(
                            new FilterItemInfo("pbulicityStatus", "1", CompareType.EQUALS));
                }
            } else {
                // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                // filerInfo.getFilterItems().add(
                // new FilterItemInfo("endTime","{ts '" + format.format(new Date())
                // + "  00:00:00'}", CompareType.GREATER_EQUALS));
            }
        } catch (EASBizException e) {
            e.printStackTrace();
        } catch (BOSException e) {
            e.printStackTrace();
        }
        return filerInfo;
    }

    public String cancelPublicityAction(HttpServletRequest request, HttpServletResponse response,
            ModelMap modelMap) throws SHRWebException {
        Context ctx = SHRContext.getInstance().getContext();
        String billId = request.getParameter("billId");
        Map<String, Object> data = new HashMap<String, Object>();
        try {
            QualiPublicityRelationCollection colls = QualiPublicityRelationFactory.getLocalInstance(ctx)
                    .getQualiPublicityRelationCollection("where id = '" + billId + "'");
            if (colls.size() > 0) {
                for (int i = 0, size = colls.size(); i < size; i++) {
                    QualiPublicityRelationInfo info = colls.get(i);
                    SelectorItemCollection iselColl = new SelectorItemCollection();
                    info.setPbulicityStatus(PublicityStatusEnum.CANCLE);
                    iselColl.add("pbulicityStatus");
                    QualiPublicityRelationFactory.getLocalInstance(ctx).updatePartial(info, iselColl);
                    QualiPublicityRelationEntryCollection entrys = info.getEntrys();
                    String personId = "('";
                    String applyBillId = "('";
                    String summaryBillId = "('";
                    for (int x = 0, len = entrys.size(); x < len; x++) {
                        QualiPublicityRelationEntryInfo entry = entrys.get(x);
                        personId = personId + entry.getPerson().getId() + "','";
                        applyBillId = applyBillId + entry.getQuaApplyBillId() + "','";
                        summaryBillId = summaryBillId + entry.getSummaryBillId() + "','";
                    }
                    personId = personId.substring(0, personId.length() - 2) + ")";
                    applyBillId = applyBillId.substring(0, applyBillId.length() - 2) + ")";
                    summaryBillId = summaryBillId.substring(0, summaryBillId.length() - 2) + ")";
                    PersonCollection persons = PersonFactory.getLocalInstance(ctx).getPersonCollection(
                            "where id in " + personId);
                    SummaryApprovalBillCollection sums = SummaryApprovalBillFactory.getLocalInstance(ctx)
                            .getSummaryApprovalBillCollection("where id in " + summaryBillId);
                    QualificationApplyBillCollection qabs = QualificationApplyBillFactory.getLocalInstance(
                            ctx).getQualificationApplyBillCollection("where id in " + applyBillId);
                    SelectorItemCollection pselColl = new SelectorItemCollection();
                    SelectorItemCollection sselColl = new SelectorItemCollection();
                    SelectorItemCollection qselColl = new SelectorItemCollection();
                    for (int z = 0, good = persons.size(); z < good; z++) {
                        PersonInfo person = persons.get(z);
                        SummaryApprovalBillInfo sum = sums.get(z);
                        QualificationApplyBillInfo qab = qabs.get(z);
                        person.put("presentLink", QuaApplyPresentLinkEnum.RESULT);
                        pselColl.add("presentLink");
                        PersonFactory.getLocalInstance(ctx).updatePartial(person, pselColl);
                        sum.setIsPublic(false);
                        sselColl.add("isPublic");
                        SummaryApprovalBillFactory.getLocalInstance(ctx).updatePartial(sum, sselColl);
                        qab.setPresentLink(QuaApplyPresentLinkEnum.RESULT);
                        qselColl.add("presentLink");
                        QualificationApplyBillFactory.getLocalInstance(ctx).updatePartial(qab, qselColl);
                        pselColl.clear();
                        sselColl.clear();
                        qselColl.clear();
                    }
                }
            }
        } catch (BOSException e) {
            e.printStackTrace();
        } catch (EASBizException e) {
            e.printStackTrace();
        }
        data.put("status", 200);
        JSONUtils.writeJson(response, data);
        return null;
    }
}
